package org.zuel.huhuForum.controller.interceptor;

import lombok.extern.log4j.Log4j2;
import org.apache.poi.util.StringUtil;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.util.CommunityUtil;
import org.zuel.huhuForum.util.HostHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Log4j2
@Component
public class PowerInterceptor implements HandlerInterceptor {


    @Autowired
    private HostHolder hostHolder;


    private Map<String, Integer> controller;


    PowerInterceptor(@Qualifier("contro") Map controller){
        this.controller=controller;
    }


    /**
     * 在 Controller 执行之前被调用
     * 检查凭证状态，若凭证有效则在本次请求中持有该用户信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

       String url=request.getRequestURI();
       Integer type=controller.get(url);
       if(type==null){
           return true;
       }
       User user =hostHolder.getUser();
        Integer power;
       if(user==null){
           response.setContentType("application/plain;charset=utf-8");
           PrintWriter writer = response.getWriter();
           writer.write(CommunityUtil.getJSONString(403, "普通请求，未登录"));
           log.info("未登录");
           return false;
       }else{
           power=user.getType();
       }
       if(power>=type){
           return true;
       }else {
           response.setContentType("application/plain;charset=utf-8");
           PrintWriter writer = response.getWriter();
           writer.write(CommunityUtil.getJSONString(403, "普通请求，你没有访问该功能的权限"));
           log.info("权限不够");
           return false;
       }
    }

    @Bean("contro")
    Map<String, Integer> contro(){
        Map<String, Integer> controller=new HashMap<>();
        controller.put("/login/logout", 1);
        controller.put("/discuss/add", 1);
        controller.put("/discuss/delete", 1);
        controller.put("/discuss/top", 2);
        controller.put("/discuss/update", 1);
        controller.put("/discuss/wonderful", 1);
        controller.put("/comment/add", 1);
        controller.put("/message", 1);
        return controller;
    }
}
